<template>
  <div class="app-container">
    <el-tag color="#2b85e4" style="color:white;margin-bottom:20px" size="large">
      模板信息
    </el-tag>
    <el-row :gutter="30">
      <el-col :span="24">
        <el-table
          :data="formTemplateTableData"
          border
          empty-text="暂无数据"
          style="width: 100%">
          <el-table-column
            label="模板编码"
            property="code"
            width="200">
          </el-table-column>
          <el-table-column
            label="模板名称"
            property="name"
            width="150">
          </el-table-column>
          <el-table-column
            label="模板描述"
            property="description">
          </el-table-column>
        </el-table>
      </el-col>
    </el-row>
    <br/>
    <br/>
    <el-tag color="#2b85e4" style="color:white;margin-bottom:20px" size="large">
      配置项列表
    </el-tag>
    <el-row :gutter="30">
      <el-col :span="24">
        <div>
          <el-button icon="el-icon-plus" type="primary" size="mini" @click="addData">新增</el-button>
          <el-button icon="el-icon-close" type="danger" size="mini" @click="deleteAny">删除</el-button>
        </div>
        <div class="query-form">
          <el-form ref="tableSearchParam" :model="tableSearchParam" label-width="50px" :inline="true">
            <el-form-item label="配置项编码" label-width="90px">
              <el-input v-model="tableSearchParam.code" style="width:200px" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item label="配置项名称" label-width="90px">
              <el-input v-model="tableSearchParam.name" style="width:200px" size="small" clearable></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="listTableData" icon="el-icon-search" size="small">查询</el-button>
            </el-form-item>
          </el-form>
        </div>
        <br/>
        <el-table
          :data="tableData"
          border
          empty-text="暂无数据"
          style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column
            type="selection"
            width="35">
          </el-table-column>
          <el-table-column
            label="类型"
            property="itemType"
            width="100">
          </el-table-column>
          <el-table-column
            label="配置项编码"
            property="code"
            width="200">
          </el-table-column>
          <el-table-column
            label="配置项名称"
            property="name"
            width="200">
          </el-table-column>
          <el-table-column
            property="createdTime"
            label="创建时间"
            width="150">
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                icon="el-icon-edit"
                type="success"
                @click="editData(scope.$index, scope.row)">编辑
              </el-button>
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-close"
                @click="handleDelete(scope.$index, scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="page">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page=this.currentPage
            :page-sizes="[10, 20, 30, 40]"
            :page-size=this.pageSize
            layout="total, sizes, prev, pager, next, jumper"
            :total=this.total>
          </el-pagination>
        </div>
      </el-col>
    </el-row>
    <!--选择配置项类型，表单项或表单组-->
    <el-dialog title="选择配置项类型" :visible.sync="dialogTypeFormVisible" top="10vh">
      <el-form :model="formData" style="width:400px">
        <el-form-item label="类型" :label-width="formLabelWidth">
          <el-radio v-model="formData.formItemType" label="1">表单项</el-radio>
          <el-radio v-model="formData.formItemType" label="2">表单组</el-radio>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleType">下一步</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="actionType=='add'?'新增配置项':'修改配置项'" :visible.sync="dialogFormVisible" top="10vh" width="60%">
      <!--添加表单项，表单项信息-->
      <div style="height:400px;overflow-y: auto" v-if="formData.formItemType==1">
        <el-form :model="formData" style="width:400px" :rules="operationRules" ref="operationRuleForm">
          <el-row :gutter="20" style="width:610px">
            <el-col :span="12">
              <el-form-item label="配置项编码" :label-width="formLabelWidth" prop="code">
                <el-input v-model="formData.code" auto-complete="off" style="width:200px"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="配置项名称" :label-width="formLabelWidth" prop="name">
                <el-input v-model="formData.name" auto-complete="off" style="width:200px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="width:610px">
            <el-col :span="12">
              <el-form-item label="配置项类型" :label-width="formLabelWidth" prop="controlCode">
                <el-select v-model="formData.controlCode" placeholder="请选择" no-data-text="暂无数据" style="width:200px"
                           @change="controlChange">
                  <el-option
                    v-for="item in allControlData"
                    :key="item.code"
                    :label="item.name"
                    :value="item.code">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序码" :label-width="formLabelWidth">
                <el-input v-model="formData.itemSort" auto-complete="off" style="width:200px"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" style="width:610px">
            <el-col :span="24">
              <el-form-item label="" :label-width="formLabelWidth">
                <el-row v-for="attrItem in allAttrData" :gutter="30" :key="attrItem.value">
                  <el-col :span="24">
                    {{attrItem.name}}：
                    <el-radio v-model="attrItem.value" :label="vItem"
                              v-for="vItem in (attrItem.description.split(';'))">{{vItem}}
                    </el-radio>
                  </el-col>
                </el-row>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="200">
            <el-col :span="24">
              <el-form-item label="验证规则" :label-width="formLabelWidth">
                <el-input v-model="formData.verifyRule" auto-complete="off" type="textarea" :rows="6"
                          width="500"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="200">
            <el-col :span="24">
              <el-form-item label="描述" :label-width="formLabelWidth" prop="url">
                <el-input v-model="formData.description" auto-complete="off" type="textarea" :rows="6"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>

      <!--添加表单组，表单组列表-->
      <el-form :model="formData" style="width:400px" :rules="operationRules" ref="operationRuleForm"
               v-if="formData.formItemType==2">
        <el-row :gutter="20" style="width:610px">
          <el-col :span="12">
            <el-form-item label="表单组" :label-width="formLabelWidth">
              <el-button size="small" @click="selectFormGroup">选择组</el-button>
              <label style="font-size: 12px">{{groupName}}</label>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序码" :label-width="formLabelWidth">
              <el-input v-model="formData.itemSort" auto-complete="off" style="width:200px"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleAdd" v-if="actionType=='add'" :loading="loading">保存</el-button>
        <el-button type="primary" @click="handleEdit" v-else :loading="loading">修改</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择表单组" :visible.sync="dialogGroupFormVisible" top="10vh" width="60%">
      <el-row :gutter="30">
        <el-col :span="24">
          <div>
            <el-form ref="groupTableSearchParam" :model="groupTableSearchParam" label-width="50px" :inline="true">
              <el-form-item label="组编码" label-width="70px">
                <el-input v-model="groupTableSearchParam.code" style="width:200px" size="small" clearable></el-input>
              </el-form-item>
              <el-form-item label="组名称" label-width="90px">
                <el-input v-model="groupTableSearchParam.name" style="width:200px" size="small" clearable></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="listGroupTableData" icon="el-icon-search" size="small">查询
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-table
            :data="groupTableData"
            border
            empty-text="暂无数据"
            style="width: 100%"
            @row-click="groupClick">
            <el-table-column
              label="组编码"
              property="code"
              width="200">
            </el-table-column>
            <el-table-column
              label="组名称"
              property="name"
              width="150">
            </el-table-column>
            <el-table-column
              property="createdTime"
              label="创建时间">
            </el-table-column>
          </el-table>
          <div class="page">
            <el-pagination
              @size-change="handleGroupSizeChange"
              @current-change="handleGroupCurrentChange"
              :current-page=this.groupCurrentPage
              :page-sizes="[10, 20, 30, 40]"
              :page-size=this.groupPageSize
              layout="total, sizes, prev, pager, next, jumper"
              :total=this.groupTotal>
            </el-pagination>
          </div>
        </el-col>
      </el-row>
    </el-dialog>
  </div>
</template>

<style lang="scss">
  .page {
    text-align: center;
    margin-top: 20px;
  }

  .query-form {
    border-bottom: 1px solid #ebeef5;
    padding-top: 25px;
  }

  .el-textarea__inner {
    width: 500px
  }
</style>

<script>
  import controlApi from '@/api/controlApi'
  import formItemApi from '@/api/formItemApi'
  import formTemplateApi from '@/api/formTemplateApi'
  import formTemplateConfigApi from '@/api/formTemplateConfigApi'
  import formGroupApi from '@/api/formGroupApi'


  export default {
    created() {
      this.getFormTemplateData()
      this.initData()
    },
    data() {
      return {
        groupName: '',
        attrValue: {},
        allAttrData: [],
        allControlData: [],
        formTemplateTableData: [],
        tableData: [],
        currentPage: 1,
        pageSize: 10,
        total: 0,
        tableSearchParam: {
          code: '',
          name: ''
        },
        templateId: this.$route.query.id,
        dialogFormVisible: false,
        formLabelWidth: '100px',
        formData: {
          formItemType: '1',
          code: '',
          name: '',
          controlCode: '',
          verifyRule: '',
          description: '',
          templateId: '',
          groupId: '',
          itemAttr: '',
          itemSort: ''

        },
        loading: false,
        actionType: '',
        multipleSelection: [],
        operationRules: {
          code: [
            {required: true, message: '请输入配置项编码', trigger: 'blur'},
            {max: 50, message: '长度不超过50 个字符', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请输入配置项名称', trigger: 'blur'},
            {max: 50, message: '长度不超过50 个字符', trigger: 'blur'}
          ],
          controlCode: [
            {required: true, message: '请输入配置项类型', trigger: 'blur'}
          ]

        },
        dialogTypeFormVisible: false,
        groupTableData: [],
        groupCurrentPage: 1,
        groupPageSize: 10,
        groupTotal: 0,
        groupTableSearchParam: {
          code: '',
          name: ''
        },
        dialogGroupFormVisible: false
      }
    },
    methods: {
      initData() {
        this.listTableData()
      },
      listTableData() {
        this.tableSearchParam.templateId = this.templateId
        this.tableData = []
        formTemplateConfigApi.listFormTemplateConfig(this.tableSearchParam, this.currentPage, this.pageSize, (res) => {
          for (var td of res.list) {
            let t = {
              id: '',
              code: '',
              name: '',
              itemType: '',
              createdTime: ''
            }
            t.id = td.id
            t.code = td.itemCode == null ? (td.groupCode == null ? '' : td.groupCode) : td.itemCode
            t.name = td.itemName == null ? (td.groupName == null ? '' : td.groupName) : td.itemName
            t.itemType = td.itemType == 1 ? '表单项' : '表单组'
            t.createdTime = td.createdTime
            this.tableData.push(t)
          }
          this.total = res.total
        }, () => {
        })
      },
      getFormTemplateData() {
        this.formTemplateTableData = []
        formTemplateApi.getFormTemplate(this.templateId, (res) => {
          this.formTemplateTableData.push(res)
        }, () => {
        })
      },
      addData() {
        //清空历史值
        this.formData = {
          formItemType: '1',
          code: '',
          name: '',
          controlCode: '',
          verifyRule: '',
          description: ''
        }
        this.groupName = ''
        this.attrValue = {}
        this.allAttrData = []
        this.allControlData = []
        controlApi.listAllControl({}, (res) => {
          this.allControlData = res
          this.formData.templateId = this.templateId
          this.actionType = 'add'
          this.dialogTypeFormVisible = true
          this.dialogFormVisible = false
        }, () => {

        })
      },
      handleAdd(event) {
        this.setItemAttr()
        this.$refs['operationRuleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            formItemApi.addFormItem(this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '添加成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },
      editData(index, row) {
        //清空历史值
        this.formData = {
          code: '',
          name: '',
          controlCode: '',
          verifyRule: '',
          description: ''
        }
        let that = this
        that.actionType = 'edit'

        formTemplateConfigApi.getFormTemplateConfig(row.id, (res1) => {
          if (res1.formItemType == '1') {
            that.formData = res1
            this.allControlData = res1.allControl
            this.setAllAttrData(res1.controlCode)
          } else {
            this.formData.formItemType = res1.formItemType
            this.formData.groupId = res1.code
            this.groupName = res1.name
            this.formData.itemSort = res1.itemSort
          }

          that.formData.id = row.id
          that.dialogFormVisible = true
        }, () => {

        })
      },
      handleEdit() {

        this.setItemAttr()

        this.$refs['operationRuleForm'].validate((valid) => {
          if (valid) {
            this.loading = true
            formItemApi.updateFormItem(this.formData.id, this.formData, (res) => {
              this.loading = false
              this.dialogFormVisible = false
              this.$message({
                message: '修改成功',
                type: 'success'
              })
              this.initData()
            }, () => {
              this.loading = false
            })
          }
        })
      },

      setItemAttr() {
        this.formData.itemAttr = []
        for (var ad of this.allAttrData) {
          const a = {
            key: '',
            value: ''
          }
          a.key = ad.code
          a.value = ad.value
          this.formData.itemAttr.push(a)
        }
      },

      setAllAttrData(code) {
        this.allAttrData = []
        for (var acd of this.allControlData) {
          if (acd.code == code) {
            this.allAttrData = acd.attr
            break;
          }
        }
      },
      handleDelete(index, row) {
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          formTemplateConfigApi.deleteSingleFormTemplateConfig(row.id, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.listTableData()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        this.listTableData()
      },
      searchTableData() {

      },
      handleSelectionChange(val) {
        this.multipleSelection = []
        for (var ms of val) {
          this.multipleSelection.push(ms.id)
        }
      },
      deleteAny() {
        if (this.multipleSelection.length == 0) {
          this.$message({
            type: 'warning',
            message: '请选择记录!'
          })
          return;
        }
        this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          formTemplateConfigApi.removeFormTemplateConfig(this.multipleSelection, (res) => {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.initData()
          }, () => {
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
      },
      listGroupTableData() {
        formGroupApi.listFormGroup(this.groupTableSearchParam, this.groupCurrentPage, this.groupPageSize, (res) => {
          this.groupTableData = res.list
          this.groupTotal = res.total
        }, () => {
        })
      },
      handleType() {
        if (this.formItemType == '1') {
          this.dialogTypeFormVisible = false
          this.dialogFormVisible = true
        } else {
          formGroupApi.listFormGroup(this.groupTableSearchParam, this.groupCurrentPage, this.groupPageSize, (res) => {
            this.groupTableData = res.list
            this.groupTotal = res.total
            this.dialogTypeFormVisible = false
            this.dialogFormVisible = true
          }, () => {
          })
        }

      },
      controlChange(value) {
        this.setAllAttrData(value)
      },

      handleGroupSizeChange(val) {
        this.groupPageSize = val
        this.listGroupTableData()
      },
      handleGroupCurrentChange(val) {
        this.groupCurrentPage = val
        this.listGroupTableData()
      },
      selectFormGroup() {
        this.dialogGroupFormVisible = true
      },
      groupClick(row, event, column) {
        this.formData.groupId = row.id
        this.groupName = row.name
        this.dialogGroupFormVisible = false
      }
    }
  }
</script>
